package com.zqs.grainmall.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.bouncycastle.cert.ocsp.Req;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @program: grain-mall
 * @description:  解决feign远程调用丢失请求头的问题
 * @author: Mr.Zhang
 * @create: 2020-11-21 16:21
 **/

@Configuration
public class GrainmallFeginConfig {

    @Bean("requestInterceptor")
    public RequestInterceptor  requestInterceptor(){

        //重写拦截器
       return new RequestInterceptor(){

           @Override
           public void apply(RequestTemplate template) {
               //使用RequestContextHolder拿到刚进来的这个请求
               ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
               if (requestAttributes!=null)
               {
                   HttpServletRequest request = requestAttributes.getRequest();  //老请求(带cookie) ,如果不同步的话fegin会自己创建一个默认的新请求，里面没有cookie

                   if (request!=null) {
                       //同步请求头数据  Cookie
                       String cookie = request.getHeader("Cookie");
                       //给新请求同步了老请求的cookie
                       template.header("Cookie", cookie);
                   }
                   System.out.println("feign远程之前先执行RequestInterceptor.apply方法");

               }

           }
       };
    }

}
